package com.bp.hearthealth.pulse.lnapps

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.os.Build
import android.text.TextUtils
import android.webkit.WebView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.multidex.MultiDex
import androidx.multidex.MultiDexApplication
import com.anythink.core.api.ATSDK
import com.anythink.splashad.api.ATSplashAd
import com.bp.hearthealth.pulse.lnapps.ads.admob.open_ad.AdMobOpenAdManager
import com.bp.hearthealth.pulse.lnapps.ads.admob.open_ad.AppForegroundHelper
import com.bp.hearthealth.pulse.lnapps.ads.admob.open_ad.OnShowAdCompleteListener
import com.bp.hearthealth.pulse.lnapps.ads.timer.AppTimer
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsSwitch
import com.bp.hearthealth.pulse.lnapps.ads.topon.open_ad.SplashAdShowActivity
import com.bp.hearthealth.pulse.lnapps.ads.topon.open_ad.TopOnOpenAdManager
import com.bp.hearthealth.pulse.lnapps.appsflyer.AppsFlyer
import com.bp.hearthealth.pulse.lnapps.bp_db.bp_project.BpDataBaseManager
import com.bp.hearthealth.pulse.lnapps.bp_di.baseLib
import com.bp.hearthealth.pulse.lnapps.bp_di.blLibe
import com.bp.hearthealth.pulse.lnapps.bp_di.genderLib
import com.bp.hearthealth.pulse.lnapps.bp_di.guideHomeLib
import com.bp.hearthealth.pulse.lnapps.bp_di.heartRateLib
import com.bp.hearthealth.pulse.lnapps.bp_di.homeLib
import com.bp.hearthealth.pulse.lnapps.bp_di.lifeStyleLib
import com.bp.hearthealth.pulse.lnapps.bp_di.meLib
import com.bp.hearthealth.pulse.lnapps.bp_di.pressureLib
import com.bp.hearthealth.pulse.lnapps.bp_di.trackerLib
import com.bp.hearthealth.pulse.lnapps.bp_extension.BpGlobalUtil
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bp.hearthealth.pulse.lnapps.bp_utils.MultiLanguageUtils
import com.bp.hearthealth.pulse.lnapps.bp_utils.MultiLanguageUtils.changeAppLanguage
import com.bp.hearthealth.pulse.lnapps.bp_utils.MultiLanguageUtils.isSameWithSetting
import com.bp.hearthealth.pulse.lnapps.bp_utils.SpUtils
import com.bp.hearthealth.pulse.lnapps.bp_view.BPNoStatusFooter
import com.bp.hearthealth.pulse.lnapps.firbase.FireBaseUtils
import com.bp.hearthealth.pulse.lnapps.notification.NotificationClickActivity
import com.hjq.toast.Toaster
import com.hjq.toast.style.BlackToastStyle
import com.scwang.smart.refresh.header.MaterialHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import me.jessyan.autosize.AutoSizeConfig
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.startKoin
import java.util.Locale


class BpApplication : MultiDexApplication(), LifecycleObserver {
    private var isFirstLaunch = true

    override fun attachBaseContext(base: Context) {
        //系统语言等设置发生改变时会调用此方法，需要要重置app语言
        super.attachBaseContext(MultiLanguageUtils.attachBaseContext(base))
        MultiDex.install(this)
    }

    override fun onCreate() {
        super.onCreate()
        context = this
        LogUtil.i("创建Application")
        //TopOn  预置策略
        ATSDK.setLocalStrategyAssetPath(this, "localStrategy")
        appForegroundHelper = AppForegroundHelper()
        appForegroundHelper!!.init(this)
        BpDataBaseManager.getInstance().init(context)
        initKoin()
        AutoSizeConfig.getInstance().isCustomFragment = true
        Toaster.init(this, BlackToastStyle())
        changeLanguage()
        initWebView()
        ProcessLifecycleOwner.get().lifecycle.addObserver(this)
        initAdMob()
    }

    private fun initAdMob() {
        AdsSwitch.initListener()
        adMobOpenAdManager = AdMobOpenAdManager()
        initSmartRefreshLayout()
        AppTimer.start()
    }

    //koin
    private fun initKoin() {
        startKoin {
            androidLogger()
            androidContext(this@BpApplication)
            modules(
                arrayListOf(
                    homeLib,
                    genderLib,
                    meLib,
                    guideHomeLib,
                    heartRateLib,
                    lifeStyleLib,
                    trackerLib,
                    blLibe,
                    pressureLib,
                    baseLib,
                )
            )
        }
    }

    companion object {
        lateinit var context: Application
        var adMobOpenAdManager: AdMobOpenAdManager? = null
        var firebaseActivate: Boolean = false

        var appForegroundHelper: AppForegroundHelper? = null
        var adIsShow = false
    }

    private fun changeLanguage() {
        val spLanguage = SpUtils.getString(applicationContext, Constants.LOCALE_LANGUAGE)!!
        val spCountry = SpUtils.getString(applicationContext, Constants.LOCALE_COUNTRY)!!
        if (!TextUtils.isEmpty(spLanguage) && !TextUtils.isEmpty(spCountry)) {
            // 如果有一个不同
            if (!isSameWithSetting(this)) {
                val locale = Locale(spLanguage, spCountry)
                changeAppLanguage(applicationContext, locale, false)
            }
        }
    }

    private fun initWebView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val processName = getProcessName()
            if (processName != null) {
                if (processName != packageName) {
                    WebView.setDataDirectorySuffix(processName)
                }
            }
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onMoveToForeground() {
        if (!isFirstLaunch) {
            val currentActivity = appForegroundHelper!!.getCurrentActivity() ?: return
            val simpleName = currentActivity.javaClass.simpleName
            LogUtil.i("onMoveToForeground  $simpleName")
            if (!AdsSwitch.getBoolean(AdsSwitch.adOpenControl)) {
                return
            }
            //插页/激励广告正在展示
            if (adIsShow) {
                return
            }
            if (currentActivity is NotificationClickActivity) {
                return
            }
//            ATSplashAd.entryAdScenario(Constants.TOP_ON_App_Open, AdConst.SCENARIO_ID.SPLASH_AD_SCENARIO)
            LogUtil.iTopOn("后台切换 isAdReady")
            if (TopOnOpenAdManager.isAdReady()) {
                currentActivity.startActivity(
                    Intent(
                        currentActivity,
                        SplashAdShowActivity::class.java
                    )
                )
//                currentActivity.overridePendingTransition(R.anim.fade_in, 0)
            } else {
//                currentActivity.let { adMobOpenAdManager?.showAdIfAvailable(it) }

//                TopOnOpenAdManager.loadAd()
                LogUtil.iTopOn("后台切换 开屏未准备好")
            }
        }
        isFirstLaunch = false
    }

    fun showAdIfAvailable(activity: Activity, onShowAdCompleteListener: OnShowAdCompleteListener) {
        adMobOpenAdManager?.showAdIfAvailable(activity, onShowAdCompleteListener)
    }

    private fun initSmartRefreshLayout() {
        SmartRefreshLayout.setDefaultRefreshInitializer { context, layout ->
            layout.setEnableLoadMore(true)
            layout.setEnableLoadMoreWhenContentNotFull(true)
        }

        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout ->
            layout.setEnableHeaderTranslationContent(true)
            MaterialHeader(context).setColorSchemeResources(
                R.color.blue, R.color.blue, R.color.blue
            )
        }

        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, layout ->
            layout.setEnableFooterFollowWhenNoMoreData(true)
            layout.setEnableFooterTranslationContent(true)
            layout.setFooterHeight(153f)
            layout.setFooterTriggerRate(0.6f)
            BPNoStatusFooter.REFRESH_FOOTER_NOTHING =
                BpGlobalUtil.getString(R.string._footer_not_more_str)
            BPNoStatusFooter(context).apply {
                setAccentColorId(R.color.color_027FFB)
                setTextTitleSize(16f)
            }
        }
    }
}